//
//  CLInputView.m
//  AFNTest
//
//  Created by louis on 15/9/25.
//  Copyright (c) 2015年 qiuwei. All rights reserved.
//

#import "CLInputView.h"

// 键盘高度
#define kKeyBoardHeight 216
// 键盘动画时间
#define kKeyBoardDuration 0.25

@interface CLInputView()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UILabel *errorLabel;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIButton *okBtn;

- (IBAction)cancel;
- (IBAction)sure;

// 最大输入长度
@property (nonatomic, assign) int maxLength;
// textField上一次的文字
@property (nonatomic, copy) NSString *lastStr;

@property (nonatomic, copy) NSString *title;
@property (nonatomic, assign) CLInputViewInputType type;
@property (nonatomic, copy) CLInputViewCompletionBlock completion;
@end

@implementation CLInputView

+ (instancetype)inputViewWithTitle:(NSString *)title type:(CLInputViewInputType)inputType completion:(CLInputViewCompletionBlock)completion
{
    CLInputView *view = [[self alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.titleLabel.text = [NSString stringWithFormat:@"%@%@", CLLocalizedString(@"Edit", nil), title];
    view.type = inputType;
    view.completion = completion;
    [view.cancelBtn setTitle:CLLocalizedString(@"Cancel", nil) forState:UIControlStateNormal];
    [view.okBtn setTitle:CLLocalizedString(@"OK", nil) forState:UIControlStateNormal];
    
    // 设置placeholder属性
//    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
//    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:10];
//    view.textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:view.textField.placeholder attributes:attrs];
    
    return view;
}

- (void)setType:(CLInputViewInputType)type
{
    _type = type;
    
    // 提示语言
    if (type == CLInputViewInputType_text) {
        self.textField.placeholder = [NSString stringWithFormat:CLLocalizedString(@"InputTip", nil), 10];
        self.maxLength = 10;
    }
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor colorWithWhite:0.25 alpha:0.3];
        self.alpha = 0.0;
        
        CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
        CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
        // 子控件
        UIView *input = [[[NSBundle mainBundle] loadNibNamed:@"CLInputView" owner:self options:nil] lastObject];
        CGFloat inputH = input.frame.size.height;
        CGFloat inputX = screenW * 0.5;
        
        CGFloat inputY = 0.0;
        inputY = screenH - kKeyBoardHeight - 100 - 0.5*inputH;
     
        input.center = CGPointMake(inputX, inputY);
        [self addSubview:input];
        
        // 输入框设定
//        self.textField.delegate = self;
        self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.textField.returnKeyType = UIReturnKeyDone;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:) name:UITextFieldTextDidChangeNotification object:self.textField];
    }
    return self;
}

- (void)hidden
{
    [self.textField endEditing:YES];
    [UIView animateWithDuration:kKeyBoardDuration animations:^{
        self.alpha = 0.0;
    }];
    
    [self removeFromSuperview];
}

- (void)show
{
    UIView *view = [[UIApplication sharedApplication].windows lastObject];
    [view addSubview:self];
    [self.textField becomeFirstResponder];
    
    [UIView animateWithDuration:kKeyBoardDuration animations:^{
        self.alpha = 1.0;
    }];
}

- (IBAction)cancel
{
    [self hidden];
}

- (IBAction)sure
{
    if (self.textField.text.length < 1) {
        self.errorLabel.text = CLLocalizedString(@"noEmpty", nil);
        self.errorLabel.hidden = NO;
    } else {
        [self hidden];
        
        if (self.completion) {
            self.completion(self.textField.text);
        }
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - UITextFieldDelegate
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//    //    NSLog(@"%@-- %ld",string, range.length);
//    if (self.type == CLInputViewInputType_text) { // 文本类型
//        // 正则匹配，支持输入英文，中文，-_符号
//        NSString * regex = @"^[A-Za-z0-9\u4E00-\u9FA5_-]$";
//        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
//        BOOL isMatch = [pred evaluateWithObject:string];
//        // range.length > 0 为删除键输入
//        // \n 为回车键输入
//        if (!isMatch && !(range.length > 0) && ![string isEqualToString:@"\n"]) {
//            self.errorLabel.text = @"不能输入符号";
//            self.errorLabel.hidden = NO;
//            return NO;
//        }
//    }
//   
//    return YES;
//}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self sure];
    return YES;
}

// 判断输入的长度，有中英文输入法的区别
- (void)textFiledEditChanged:(NSNotification *)nf
{
    
    self.errorLabel.hidden = YES;
    //    NSLog(@"%@", [nf.object text]);
    UITextField *textField = (UITextField *)nf.object;
    NSString *toBeString = textField.text;
    if (toBeString.length > 0) {
        [self.okBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    }else{
        [self.okBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang hasPrefix:@"zh-"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            
            // 正则匹配，支持输入英文，中文，-_符号
            NSString * regex = @"^[a-zA-Z0-9\u4e00-\u9fa5]*";
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
            BOOL isMatch = [pred evaluateWithObject:toBeString];
            // range.length > 0 为删除键输入
            // \n 为回车键输入
            // “ ”为空格
            if (!isMatch || ([toBeString rangeOfString:@" "].location != NSNotFound)) {
                self.errorLabel.text = CLLocalizedString(@"WordSupport", nil);
                self.errorLabel.hidden = NO;
                textField.text = self.lastStr;
                return;
            }
            
            if (toBeString.length > self.maxLength) {
                textField.text = [toBeString substringToIndex:self.maxLength];
                self.errorLabel.text = CLLocalizedString(@"TooLong", nil);
                self.errorLabel.hidden = NO;
                return;
            }
            
            self.lastStr = textField.text;
            
        } else { // 有高亮选择的字符串，则暂不对文字进行统计和限制
            
            
        } 
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > self.maxLength) {
            textField.text = [toBeString substringToIndex:self.maxLength];
            self.errorLabel.text = CLLocalizedString(@"TooLong", nil);
            self.errorLabel.hidden = NO;
            return;
        }
        
        // 正则匹配，支持输入英文，中文，-_符号
        NSString * regex = @"^[a-zA-Z0-9\u4e00-\u9fa5]*";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        BOOL isMatch = [pred evaluateWithObject:toBeString];
        // range.length > 0 为删除键输入
        // \n 为回车键输入
        // “ ”为空格
        ;
        if (!isMatch || ([toBeString rangeOfString:@" "].location != NSNotFound)) {
            self.errorLabel.text = CLLocalizedString(@"WordSupport", nil);
            self.errorLabel.hidden = NO;
            textField.text = self.lastStr;
            return;
        }
    }
}

@end
